<template>
    <div class="default-main ba-table-box">
        <el-drawer
            title="添加景点"
            v-model="Table_data.table.extend!.showInfo"
            size="70%"
            show-close
            :withHeader="false"
        >
            <el-form
                label-width="77px"
                style="margin-top: 30px"
                class="ele-form-search"
                @submit.native.prevent
            >

                <span class="date-title">{{ currentMonthYear }}</span>

                <div style="display: flex;justify-content: center;align-items: center;margin-bottom: 10px">
                    <el-button @click="changeMonth(-1)">上一月</el-button>
                    <el-button @click="changeMonth(1)">下一月</el-button>
                </div>

            </el-form>

            <div class="calendar">
                <div class="calendar-grid">
                    <div
                        v-for="day in daysInMonth"
                        :key="day.date"
                        :class="['calendar-day', { 'disabled': day.isDisabled }]"
                    >
                        <h1 >{{ day.date }}号</h1>
                        <input
                            style="color: red;font-weight: bold;text-align: center;font-size: 15px;::placeholder { font-size: 4px; font-style: italic; }"
                            v-model="day.price"
                            :placeholder="'请输入价格'"
                            class="price-input"
                            :disabled="day.isDisabled"
                            @change="handleBlur(day)"
                        />
                    </div>
                </div>
            </div>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, inject, provide } from 'vue';
import { ElMessage } from 'element-plus';
import createAxios from "/@/utils/axios";
import { useI18n } from 'vue-i18n';
import type { FormInstance } from 'element-plus';
import Table2 from '/@/components/table/index.vue';
import baTableClass3 from '/@/utils/baTable';

const { t } = useI18n();
const Table_data = inject('baTable') as any;

const currentDate = ref(new Date());
const daysInMonth = ref<any[]>([]);
const prices = ref<any[]>([]);  // 存储从后端获取的价格数据

const currentMonthYear = computed(() => {
    const options = { year: 'numeric', month: 'long' };
    return currentDate.value.toLocaleDateString('zh-CN', options);
});

// 获取后端数据的模拟函数（你需要替换成实际请求代码）
const fetchPriceData = async () => {
    try {

        const res = await getPrice();
        prices.value = res.data
        updateDaysInMonth();
    } catch (error) {
        console.error('获取价格数据失败:', error);
    }
};

const getPrice = () => {
    return createAxios(
        {
            url: '/admin/hotel.Hotel/getPrice',
            method: 'POST',
            data:{hotel_id:props.selectedId}
        },
        {
            loading: true,
        }
    );
};


// 更新每月的天数和价格
const updateDaysInMonth = () => {
    const startOfMonth = new Date(currentDate.value.getFullYear(), currentDate.value.getMonth(), 1);
    const endOfMonth = new Date(currentDate.value.getFullYear(), currentDate.value.getMonth() + 1, 0);
    daysInMonth.value = [];
    const today = new Date();

    // 填充天数
    for (let i = 1; i <= endOfMonth.getDate(); i++) {
        const dayDate = new Date(currentDate.value.getFullYear(), currentDate.value.getMonth(), i);
        const dayData = prices.value.find(item => item.date === `${currentDate.value.getFullYear()}-${(currentDate.value.getMonth() + 1).toString().padStart(2, '0')}-${i.toString().padStart(2, '0')}`);

        daysInMonth.value.push({
            date: i,
            price: dayData ? dayData.price : '',  // 如果有价格数据，则显示价格，否则为空
            isDisabled: dayDate < today // 禁用过去的日期
        });
    }
};

const changeMonth = (offset: number) => {
    currentDate.value = new Date(currentDate.value.getFullYear(), currentDate.value.getMonth() + offset, 1);
    updateDaysInMonth();
};



const props = defineProps({
    selectedId: String // 接受一个初始 ID 来触发数据加载
});

watch(() => props.selectedId, (newId) => {
    if (newId) {
        fetchPriceData();  // 获取价格数据
    }
}, {immediate: true});

// 处理输入框失去焦点的事件
const handleBlur = async (day: any) => {
        try {
            // 拼接完整的日期字符串
            const fullDate = `${currentDate.value.getFullYear()}-${(currentDate.value.getMonth() + 1).toString().padStart(2, '0')}-${day.date.toString().padStart(2, '0')}`;
            await addPrice(fullDate,day.price);
        } catch (error) {
            ElMessage.error('保存失败，请重试!');
        }

};


const addPrice = (day:string,price:string) => {
    return createAxios(
        {
            url: '/admin/hotel.Hotel/addPrice',
            method: 'POST',
            data:{hotel_id:props.selectedId,date:day,price:price}
        },
        {
            showSuccessMessage: true,
            loading: true,
            showCodeMessage: true,
            showErrorMessage: true,
        }
    );
};


// 保存价格到后端
const savePrice = async (date: string, price: number) => {
    try {
        // 使用 Axios 发送价格数据到后端
        const response = await createAxios.post('/api/savePrice', {
            date,
            price
        });
        return response.data;
    } catch (error) {
        throw new Error('保存价格时发生错误');
    }
};

watch(() => Table_data.table.extend!.showInfo, (newVal) => {
    if (newVal) {
        console.log("弹窗打开");
    }
});

provide('baTable', Table_data);
</script>

<style scoped lang="scss">
.calendar {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
}

.calendar-header {
    display: flex;
    justify-content: space-between;
    width: 300px;
    margin-bottom: 10px;
}

.calendar-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    grid-gap: 10px;
    width: 100%;
}

.calendar-day {
    text-align: center;
    padding: 10px;
    border: 1px solid #ccc;
    position: relative;
    transition: background-color 0.3s ease;
    border-radius: 8px;
}

.calendar-day.disabled {
    background-color: #f0f0f0;
}

.date {
    font-weight: bold;
}

.price-input {
    width: 100%;
    padding: 5px;
    margin-top: 5px;
    border: 1px solid #ccc;
    border-radius: 4px;
}

.price-input:disabled {
    background-color: #e0e0e0;
    cursor: not-allowed;
}

.price-input::placeholder {
    font-size: 12px;
    color: #92969a;
    letter-spacing: 1px;
}

.ele-form-actions {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.date-title {
    font-size: 20px;
    color: red;
    margin-right: 30px;
    font-weight: bold;
    padding-left: 20px;
}

</style>
